Page({
  data: {
    // 游戏状态
    isPlaying: false,
    gameOver: false,
    score: 0,
    highScore: 0,
    isNewRecord: false,
    showControls: true, // 显示移动控制按钮
    
    // 游戏参数
    rows: 15, // 行数
    cols: 10, // 列数
    cellSize: 40, // 每个方块的大小(rpx)
    
    // 游戏数据
    gameBoard: [], // 游戏主面板
    currentBlock: null, // 当前方块
    nextBlock: null, // 下一个方块
    timer: null, // 游戏定时器
    dropInterval: 1000, // 下落间隔(ms)
    
    // 触摸控制
    touchStartX: 0,
    touchStartY: 0,
    touchThreshold: 30 // 触摸滑动阈值
  },
  
  onLoad() {
    // 初始化游戏
    this.initGame();
    // 获取最高分
    const highScore = wx.getStorageSync('tetrisHighScore') || 0;
    this.setData({ highScore });
  },
  
  // 初始化游戏
  initGame() {
    // 创建空游戏面板
    const gameBoard = Array(this.data.rows).fill().map(() => 
      Array(this.data.cols).fill(0)
    );
    
    // 生成第一个方块和下一个方块
    const currentBlock = this.createRandomBlock();
    const nextBlock = this.createRandomBlock();
    
    this.setData({
      gameBoard,
      currentBlock,
      nextBlock,
      score: 0,
      gameOver: false,
      isNewRecord: false
    });
    
    // 绘制游戏和下一个方块
    this.drawGame();
    this.drawNextBlock();
  },
  
  // 开始/暂停游戏
  startGame() {
    if (this.data.isPlaying) {
      // 暂停游戏
      clearInterval(this.data.timer);
      this.setData({ isPlaying: false });
    } else {
      // 开始游戏
      this.setData({ isPlaying: true });
      this.startTimer();
    }
  },
  
  // 重置游戏
  resetGame() {
    // 清除定时器
    clearInterval(this.data.timer);
    // 重新初始化游戏
    this.initGame();
    // 开始游戏
    this.setData({ isPlaying: true });
    this.startTimer();
  },
  
  // 开始定时器
  startTimer() {
    const timer = setInterval(() => {
      this.moveDown();
    }, this.data.dropInterval);
    
    this.setData({ timer });
  },
  
  // 创建随机方块
  createRandomBlock() {
    // 方块形状和颜色定义
    const blockTypes = [
      // I型
      {
        shape: [
          [1, 1, 1, 1]
        ],
        color: '#00ffff'
      },
      // O型
      {
        shape: [
          [1, 1],
          [1, 1]
        ],
        color: '#ffff00'
      },
      // T型
      {
        shape: [
          [0, 1, 0],
          [1, 1, 1]
        ],
        color: '#800080'
      },
      // S型
      {
        shape: [
          [0, 1, 1],
          [1, 1, 0]
        ],
        color: '#00ff00'
      },
      // Z型
      {
        shape: [
          [1, 1, 0],
          [0, 1, 1]
        ],
        color: '#ff0000'
      },
      // J型
      {
        shape: [
          [1, 0, 0],
          [1, 1, 1]
        ],
        color: '#0000ff'
      },
      // L型
      {
        shape: [
          [0, 0, 1],
          [1, 1, 1]
        ],
        color: '#ff7f00'
      }
    ];
    
    // 随机选择一种方块
    const typeIndex = Math.floor(Math.random() * blockTypes.length);
    const blockType = blockTypes[typeIndex];
    
    // 初始位置（居中）
    const x = Math.floor((this.data.cols - blockType.shape[0].length) / 2);
    const y = 0;
    
    return {
      shape: blockType.shape,
      color: blockType.color,
      x,
      y
    };
  },
  
  // 绘制游戏
  drawGame() {
    const ctx = wx.createCanvasContext('gameCanvas', this);
    const { rows, cols, cellSize, gameBoard, currentBlock } = this.data;
    
    // 清空画布
    ctx.clearRect(0, 0, cols * cellSize, rows * cellSize);
    
    // 绘制游戏面板已落下的方块
    for (let y = 0; y < rows; y++) {
      for (let x = 0; x < cols; x++) {
        if (gameBoard[y][x]) {
          this.drawCell(ctx, x, y, gameBoard[y][x], cellSize);
        }
      }
    }
    
    // 绘制当前方块
    if (currentBlock) {
      const { shape, color, x: blockX, y: blockY } = currentBlock;
      for (let y = 0; y < shape.length; y++) {
        for (let x = 0; x < shape[y].length; x++) {
          if (shape[y][x]) {
            this.drawCell(ctx, blockX + x, blockY + y, color, cellSize);
          }
        }
      }
    }
    
    ctx.draw();
  },
  
  // 绘制下一个方块
  drawNextBlock() {
    const ctx = wx.createCanvasContext('nextCanvas', this);
    const { nextBlock, cellSize } = this.data;
    
    // 清空画布
    ctx.clearRect(0, 0, 200, 200);
    
    if (nextBlock) {
      const { shape, color } = nextBlock;
      // 计算居中位置
      const startX = (200 - shape[0].length * cellSize) / 2;
      const startY = (200 - shape.length * cellSize) / 2;
      
      // 绘制方块
      for (let y = 0; y < shape.length; y++) {
        for (let x = 0; x < shape[y].length; x++) {
          if (shape[y][x]) {
            ctx.setFillStyle(color);
            ctx.fillRect(
              startX + x * cellSize, 
              startY + y * cellSize, 
              cellSize - 1, 
              cellSize - 1
            );
          }
        }
      }
    }
    
    ctx.draw();
  },
  
  // 绘制单个方块
  drawCell(ctx, x, y, color, cellSize) {
    ctx.setFillStyle(color);
    ctx.fillRect(
      x * cellSize, 
      y * cellSize, 
      cellSize - 1, 
      cellSize - 1
    );
  },
  
  // 移动方块向左
  moveLeft() {
    if (!this.data.isPlaying || this.data.gameOver) return;
    
    const newX = this.data.currentBlock.x - 1;
    if (this.isValidMove(newX, this.data.currentBlock.y, this.data.currentBlock.shape)) {
      const currentBlock = { ...this.data.currentBlock, x: newX };
      this.setData({ currentBlock });
      this.drawGame();
    }
  },
  
  // 移动方块向右
  moveRight() {
    if (!this.data.isPlaying || this.data.gameOver) return;
    
    const newX = this.data.currentBlock.x + 1;
    if (this.isValidMove(newX, this.data.currentBlock.y, this.data.currentBlock.shape)) {
      const currentBlock = { ...this.data.currentBlock, x: newX };
      this.setData({ currentBlock });
      this.drawGame();
    }
  },
  
  // 移动方块向下
  moveDown() {
    if (!this.data.isPlaying || this.data.gameOver) return;
    
    const newY = this.data.currentBlock.y + 1;
    if (this.isValidMove(this.data.currentBlock.x, newY, this.data.currentBlock.shape)) {
      const currentBlock = { ...this.data.currentBlock, y: newY };
      this.setData({ currentBlock });
      this.drawGame();
    } else {
      // 不能移动，固定当前方块
      this.fixBlock();
    }
  },
  
  // 快速下落到底部
  dropToBottom() {
    if (!this.data.isPlaying || this.data.gameOver) return;
    
    let newY = this.data.currentBlock.y;
    // 找到可以下落的最大距离
    while (this.isValidMove(this.data.currentBlock.x, newY + 1, this.data.currentBlock.shape)) {
      newY++;
    }
    
    if (newY !== this.data.currentBlock.y) {
      const currentBlock = { ...this.data.currentBlock, y: newY };
      this.setData({ currentBlock });
      this.drawGame();
      // 固定方块
      this.fixBlock();
    }
  },
  
  // 旋转方块
  rotateBlock() {
    if (!this.data.isPlaying || this.data.gameOver) return;
    
    const { shape } = this.data.currentBlock;
    // 旋转矩阵（顺时针90度）
    const rotatedShape = this.rotateMatrix(shape);
    
    if (this.isValidMove(this.data.currentBlock.x, this.data.currentBlock.y, rotatedShape)) {
      const currentBlock = { ...this.data.currentBlock, shape: rotatedShape };
      this.setData({ currentBlock });
      this.drawGame();
    } else {
      // 尝试墙踢（wall kick）：如果旋转后碰到右墙，向左移动
      if (this.isValidMove(this.data.currentBlock.x - 1, this.data.currentBlock.y, rotatedShape)) {
        const currentBlock = { ...this.data.currentBlock, shape: rotatedShape, x: this.data.currentBlock.x - 1 };
        this.setData({ currentBlock });
        this.drawGame();
      } 
      // 尝试墙踢：如果旋转后碰到左墙，向右移动
      else if (this.isValidMove(this.data.currentBlock.x + 1, this.data.currentBlock.y, rotatedShape)) {
        const currentBlock = { ...this.data.currentBlock, shape: rotatedShape, x: this.data.currentBlock.x + 1 };
        this.setData({ currentBlock });
        this.drawGame();
      }
    }
  },
  
  // 旋转矩阵（顺时针90度）
  rotateMatrix(matrix) {
    const rows = matrix.length;
    const cols = matrix[0].length;
    const rotated = [];
    
    for (let i = 0; i < cols; i++) {
      rotated[i] = [];
      for (let j = 0; j < rows; j++) {
        rotated[i][j] = matrix[rows - j - 1][i];
      }
    }
    
    return rotated;
  },
  
  // 检查移动是否有效
  isValidMove(x, y, shape) {
    const { rows, cols, gameBoard } = this.data;
    
    for (let row = 0; row < shape.length; row++) {
      for (let col = 0; col < shape[row].length; col++) {
        if (shape[row][col]) {
          const newX = x + col;
          const newY = y + row;
          
          // 检查是否超出边界
          if (newX < 0 || newX >= cols || newY >= rows) {
            return false;
          }
          
          // 检查是否与已有方块重叠（忽略y < 0的情况，允许方块顶部暂时超出屏幕）
          if (newY >= 0 && gameBoard[newY][newX]) {
            return false;
          }
        }
      }
    }
    
    return true;
  },
  
  // 固定当前方块到游戏面板
  fixBlock() {
    const { currentBlock, gameBoard, nextBlock, rows } = this.data;
    const newGameBoard = JSON.parse(JSON.stringify(gameBoard));
    
    // 将当前方块添加到游戏面板
    const { shape, color, x: blockX, y: blockY } = currentBlock;
    for (let y = 0; y < shape.length; y++) {
      for (let x = 0; x < shape[y].length; x++) {
        if (shape[y][x]) {
          const newX = blockX + x;
          const newY = blockY + y;
          
          // 检查游戏是否结束（方块顶部超出屏幕）
          if (newY < 0) {
            this.gameOver();
            return;
          }
          
          newGameBoard[newY][newX] = color;
        }
      }
    }
    
    // 检查并消除已满的行
    const linesCleared = this.clearLines(newGameBoard);
    
    // 更新分数
    let { score } = this.data;
    if (linesCleared > 0) {
      // 计分规则：1行100分，2行300分，3行500分，4行800分
      const lineScores = [0, 100, 300, 500, 800];
      score += lineScores[linesCleared];
      
      // 播放消除音效（实际项目中可添加）
      // wx.playBackgroundAudio({dataUrl: ''});
    }
    
    // 生成新的当前方块和下一个方块
    const newCurrentBlock = nextBlock;
    const newNextBlock = this.createRandomBlock();
    
    this.setData({
      gameBoard: newGameBoard,
      currentBlock: newCurrentBlock,
      nextBlock: newNextBlock,
      score
    });
    
    // 绘制游戏和下一个方块
    this.drawGame();
    this.drawNextBlock();
    
    // 检查新方块是否可以放置
    if (!this.isValidMove(newCurrentBlock.x, newCurrentBlock.y, newCurrentBlock.shape)) {
      this.gameOver();
    }
  },
  
  // 消除已满的行
  clearLines(board) {
    const { rows, cols } = this.data;
    let linesCleared = 0;
    
    for (let y = rows - 1; y >= 0; y--) {
      // 检查行是否已满
      let isLineComplete = true;
      for (let x = 0; x < cols; x++) {
        if (!board[y][x]) {
          isLineComplete = false;
          break;
        }
      }
      
      if (isLineComplete) {
        // 消除当前行
        for (let yy = y; yy > 0; yy--) {
          board[yy] = [...board[yy - 1]];
        }
        // 顶部添加新的空行
        board[0] = Array(cols).fill(0);
        
        linesCleared++;
        // 再次检查当前行（因为上面的行下移了）
        y++;
      }
    }
    
    return linesCleared;
  },
  
  // 游戏结束
  gameOver() {
    clearInterval(this.data.timer);
    
    // 检查是否是新纪录
    let { score, highScore } = this.data;
    let isNewRecord = false;
    
    if (score > highScore) {
      highScore = score;
      isNewRecord = true;
      // 保存新纪录
      wx.setStorageSync('tetrisHighScore', highScore);
    }
    
    this.setData({
      isPlaying: false,
      gameOver: true,
      highScore,
      isNewRecord
    });
  },
  
  // 触摸开始
  touchStart(e) {
    this.setData({
      touchStartX: e.touches[0].clientX,
      touchStartY: e.touches[0].clientY
    });
  },
  
  // 触摸移动（不处理，只在结束时判断）
  touchMove() {
    // 不做处理
  },
  
  // 触摸结束，判断滑动方向
  touchEnd(e) {
    if (!this.data.isPlaying || this.data.gameOver) return;
    
    const touchEndX = e.changedTouches[0].clientX;
    const touchEndY = e.changedTouches[0].clientY;
    
    const diffX = touchEndX - this.data.touchStartX;
    const diffY = touchEndY - this.data.touchStartY;
    
    // 判断滑动方向
    if (Math.abs(diffX) > Math.abs(diffY)) {
      // 水平滑动
      if (Math.abs(diffX) > this.data.touchThreshold) {
        if (diffX > 0) {
          this.moveRight();
        } else {
          this.moveLeft();
        }
      }
    } else {
      // 垂直滑动
      if (Math.abs(diffY) > this.data.touchThreshold) {
        if (diffY > 0) {
          this.moveDown();
        } else {
          this.rotateBlock();
        }
      }
    }
  }
});
